// API 基础路径
const API_BASE = '/api';

// 表单显示状态
let isFormVisible = false;

// 点击按钮显示表单
function cli() {
    console.log('cli() 函数被调用');
    const formContainer = document.getElementById("txt");
    
    if (formContainer) {
        console.log('找到表单容器');
        console.log('当前类名:', formContainer.className);
        
        // 直接显示表单，不管当前状态
        formContainer.classList.add('show');
        isFormVisible = true;
        
        console.log('添加show类后的类名:', formContainer.className);
        console.log('表单已显示');
    } else {
        console.error('找不到id为txt的元素');
    }
}

// 关闭表单
function closeForm() {
    console.log('closeForm() 函数被调用');
    const formContainer = document.getElementById("txt");
    if (formContainer) {
        formContainer.classList.remove('show');
        isFormVisible = false;
        console.log('表单已关闭');
        
        // 清空消息
        const messageDiv = document.getElementById('studentMessage');
        if (messageDiv) {
            messageDiv.innerHTML = '';
        }
    }
}

// 加入拼团 - 直接调用cli
function joinGroup(nickname) {
    console.log('joinGroup被调用，昵称:', nickname);
    cli();
}

// 等待页面加载完成
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，开始初始化');
    
    // 确保表单初始状态正确
    const formContainer = document.getElementById("txt");
    if (formContainer) {
        console.log('初始化时表单容器存在');
        formContainer.classList.remove('show'); // 确保初始状态是隐藏的
        isFormVisible = false;
    }
    
    // ESC键关闭表单
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && isFormVisible) {
            closeForm();
        }
    });
    
    // 表单提交处理
    const studentForm = document.getElementById('studentForm');
    if (studentForm) {
        studentForm.addEventListener('submit', function(e) {
            e.preventDefault();
            console.log('表单提交');
            
            // 获取表单数据
            const formData = {
                name: document.getElementById('name').value,
                phone: document.getElementById('phone').value,
                age: document.getElementById('age').value,
                grade: document.getElementById('grade').value
            };
            
            submitForm(formData);
        });
    }
    
    // 初始化拼团列表
    initGroupList();
    
    // 初始化拼团选项点击事件
    initGroupOptions();
    
    // 延迟检查表单提交状态
    setTimeout(checkFormSubmissionStatus, 1000);
});

// 初始化拼团列表
function initGroupList() {
    console.log('初始化拼团列表');
    
    // 随机昵称数组
    const nicknames = [
        '美丽*', '高*', '静*', '小明*', '晓雨*', '阳光*', '梦想*', '快乐*',
        '温柔*', '可爱*', '聪明*', '活泼*', '开心*', '帅气*', '优雅*', '甜美*'
    ];
    
    const groupList = document.getElementById('groupList');
    if (!groupList) {
        console.log('找不到groupList元素');
        return;
    }
    
    // 清空现有内容
    groupList.innerHTML = '';
    
    // 创建滚动容器
    const scrollContainer = document.createElement('div');
    scrollContainer.className = 'group-list-scroll';
    
    // 生成拼团项目用于滚动效果
    let html = '';
    for (let i = 0; i < 6; i++) {
        const nickname = nicknames[i % nicknames.length];
        const currentCount = Math.floor(Math.random() * 2) + 1;
        const needCount = Math.floor(Math.random() * 2) + 1;
        
        html += `
            <div class="group-item">
                <div class="user-info">
                    <img src="https://animates.oss-cn-beijing.aliyuncs.com/tcyc/avatar${(i % 3) + 1}.jpg" alt="用户头像" class="user-avatar" onerror="this.src='/static/img/avatar.jpg'">
                    <div class="user-details">
                        <div class="user-name">${nickname}</div>
                        <div class="user-badge">好友</div>
                    </div>
                </div>
                <div class="group-status">
                    <div class="group-progress">当前${currentCount}人，还差${needCount}人成团</div>
                    <button class="join-btn" onclick="cli()">去拼团</button>
                </div>
            </div>
        `;
    }
    
    // 复制内容以实现无缝滚动
    scrollContainer.innerHTML = html + html;
    groupList.appendChild(scrollContainer);
    
    // 确保内容立即可见
    setTimeout(() => {
        scrollContainer.style.opacity = '1';
    }, 100);
    
    console.log('拼团列表已生成');
}

// 初始化拼团选项点击事件
function initGroupOptions() {
    console.log('初始化拼团选项点击事件');
    
    const optionItems = document.querySelectorAll('.option-item');
    
    optionItems.forEach((item, index) => {
        item.addEventListener('click', function() {
            console.log('点击了拼团选项:', index);
            
            // 移除所有active类
            optionItems.forEach(option => {
                option.classList.remove('active');
            });
            
            // 给当前点击的添加active类
            this.classList.add('active');
            
            // 添加点击反馈动画
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = '';
            }, 150);
            
            // 可以在这里添加更多逻辑，比如更新价格显示等
            const optionDesc = this.querySelector('.option-desc').textContent;
            console.log('选择了:', optionDesc);
        });
        
        // 添加触摸反馈（移动端）
        item.addEventListener('touchstart', function() {
            this.style.transform = 'scale(0.98)';
        });
        
        item.addEventListener('touchend', function() {
            setTimeout(() => {
                this.style.transform = '';
            }, 100);
        });
    });
}

// 表单提交函数
function submitForm(formData) {
    
    // 显示提交中状态
    const submitBtn = document.getElementById('but');
    const originalText = submitBtn.textContent;
    submitBtn.innerHTML = '<span class="loading"></span>提交中...';
    submitBtn.disabled = true;
    
    // 发送真实的API请求
    fetch(`${API_BASE}/submit-form`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        console.log('表单提交成功:', data);
        
        // 恢复按钮状态
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
        
        // 显示成功消息
        const messageDiv = document.getElementById('studentMessage');
        messageDiv.innerHTML = '<div class="success">报名信息提交成功！</div>';
        
        // 保存提交状态到本地存储
        localStorage.setItem('formSubmitted', 'true');
        localStorage.setItem('submitTime', new Date().toISOString());
        localStorage.setItem('studentData', JSON.stringify(formData));
        
        // 关闭表单并显示支付模块
        setTimeout(() => {
            closeForm();
            showPaymentSection();
        }, 1500);
    })
    .catch(error => {
        console.error('表单提交失败:', error);
        
        // 恢复按钮状态
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
        
        // 显示错误消息
        const messageDiv = document.getElementById('studentMessage');
        messageDiv.innerHTML = '<div class="error">提交失败，请重试</div>';
    });
}

// 显示支付模块
function showPaymentSection() {
    console.log('显示支付模块');
    const paymentSection = document.getElementById('payment-section');
    if (paymentSection) {
        paymentSection.style.display = 'block';
        // 滚动到支付区域
        paymentSection.scrollIntoView({ 
            behavior: 'smooth',
            block: 'center'
        });
    }
}

// 检查是否已提交表单
function checkFormSubmissionStatus() {
    const isSubmitted = localStorage.getItem('formSubmitted');
    if (isSubmitted === 'true') {
        console.log('检测到已提交表单，显示支付模块');
        showPaymentSection();
    }
}

// 显示海报弹窗
function showPoster() {
    console.log('显示分享海报');
    const posterModal = document.getElementById('poster-modal');
    if (posterModal) {
        posterModal.style.display = 'flex';
        // 防止背景滚动
        document.body.style.overflow = 'hidden';
    }
}

// 关闭海报弹窗
function closePoster() {
    console.log('关闭分享海报');
    const posterModal = document.getElementById('poster-modal');
    if (posterModal) {
        posterModal.style.display = 'none';
        // 恢复背景滚动
        document.body.style.overflow = 'auto';
    }
}

// 全局暴露函数，确保HTML中的onclick可以访问
window.cli = cli;
window.closeForm = closeForm;
window.joinGroup = joinGroup;
window.submitForm = submitForm;
window.showPaymentSection = showPaymentSection;
window.showPoster = showPoster;
window.closePoster = closePoster;

console.log('JavaScript文件加载完成');

// 音乐控制功能
let backgroundMusic = null;
let musicControl = null;
let isPlaying = false;

// 初始化音乐控制
function initMusicControl() {
    backgroundMusic = document.getElementById('backgroundMusic');
    musicControl = document.getElementById('musicControl');
    
    if (!backgroundMusic || !musicControl) {
        console.log('音乐元素未找到');
        return;
    }
    
    // 设置初始状态
    musicControl.classList.add('playing');
    
    // 尝试自动播放
    const playPromise = backgroundMusic.play();
    if (playPromise !== undefined) {
        playPromise.then(() => {
            console.log('音乐开始播放');
            isPlaying = true;
            updateMusicIcon();
        }).catch(error => {
            console.log('自动播放被阻止:', error);
            isPlaying = false;
            musicControl.classList.remove('playing');
            musicControl.classList.add('paused');
            updateMusicIcon();
            
            // 用户滚动时尝试播放音乐
            const scrollHandler = () => {
                backgroundMusic.play().then(() => {
                    console.log('用户滚动后开始播放音乐');
                    document.removeEventListener('scroll', scrollHandler);
                }).catch(err => {
                    console.log('滚动后播放失败:', err);
                });
            };
            document.addEventListener('scroll', scrollHandler, { once: true });
        });
    }
    
    // 点击控制按钮
    musicControl.addEventListener('click', toggleMusic);
    
    // 监听音乐事件
    backgroundMusic.addEventListener('play', () => {
        isPlaying = true;
        musicControl.classList.remove('paused');
        musicControl.classList.add('playing');
        updateMusicIcon();
    });
    
    backgroundMusic.addEventListener('pause', () => {
        isPlaying = false;
        musicControl.classList.remove('playing');
        musicControl.classList.add('paused');
        updateMusicIcon();
    });
    
    backgroundMusic.addEventListener('ended', () => {
        isPlaying = false;
        musicControl.classList.remove('playing');
        musicControl.classList.add('paused');
        updateMusicIcon();
    });
}

// 切换音乐播放状态
function toggleMusic() {
    if (!backgroundMusic) return;
    
    if (isPlaying) {
        backgroundMusic.pause();
    } else {
        const playPromise = backgroundMusic.play();
        if (playPromise !== undefined) {
            playPromise.catch(error => {
                console.log('播放失败:', error);
            });
        }
    }
}

// 更新音乐图标
function updateMusicIcon() {
    const musicIcon = document.getElementById('musicIcon');
    if (!musicIcon) return;
    
    if (isPlaying) {
        // 播放中的图标 - 音符
        musicIcon.innerHTML = `
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M9 18V5L21 3V16" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <circle cx="6" cy="18" r="3" stroke="currentColor" stroke-width="2"/>
                <circle cx="18" cy="16" r="3" stroke="currentColor" stroke-width="2"/>
            </svg>
        `;
    } else {
        // 暂停的图标 - 静音
        musicIcon.innerHTML = `
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M11 5L6 9H2V15H6L11 19V5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <line x1="23" y1="9" x2="17" y2="15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <line x1="17" y1="9" x2="23" y2="15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
        `;
    }
}

// 页面加载完成后初始化音乐控制
document.addEventListener('DOMContentLoaded', function() {
    // 延迟初始化音乐控制，确保DOM完全加载
    setTimeout(initMusicControl, 500);
});

// 点击屏幕时尝试播放音乐
document.addEventListener('click', function onFirstUserClick() {
    if (!backgroundMusic) {
        backgroundMusic = document.getElementById('backgroundMusic');
    }
    const playPromise = backgroundMusic.play();
    if (playPromise !== undefined) {
        playPromise.then(() => {
            console.log('用户点击屏幕后播放音乐');
        }).catch(err => {
            console.log('点击后播放失败:', err);
        });
    }
}, { once: true });

// 全局暴露音乐控制函数
window.toggleMusic = toggleMusic;
window.initMusicControl = initMusicControl;
